<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>活动策划 - 贝壳OC智能应用中心</title>
    <meta name="description" content="活动策划助手，支持连续对话和历史记录">
    <link rel="stylesheet" href="chat-styles.css">
    <script src="config.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap"
        rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
</head>

<body>
    <!-- 返回按钮 -->
    <div class="back-button" onclick="window.location.href='index.html'">
        <span>←</span> 返回首页
    </div>

    <!-- 主容器 -->
    <div class="chat-container">
        <!-- 头部 -->
        <div class="chat-header">
            <div class="chat-title">
                <div class="chat-icon">🎯</div>
                <h1>活动策划助手</h1>
                <div class="chat-status online">在线</div>
            </div>
            <div class="chat-actions">
                <button class="action-btn" onclick="clearHistory()" title="清空历史">
                    <span>🗑️</span>
                </button>
                <button class="action-btn" onclick="exportHistory()" title="导出对话">
                    <span>📤</span>
                </button>
            </div>
        </div>

        <!-- 对话区域 -->
        <div class="chat-messages" id="chatMessages">
            <div class="welcome-message">
                <div class="message bot-message">
                    <div class="message-avatar">🤖</div>
                    <div class="message-content">
                        <div class="message-text">
                            您好！我是活动策划智能助手，专门帮助您智能生成活动方案，一键创建完整活动流程，助力高效活动策划与执行。我可以为您提供活动主题设计、流程规划、预算分析、资源配置等全方位的策划支持。请告诉我您想要策划什么类型的活动？
                        </div>
                        <div class="message-time">刚刚</div>
                        <div class="message-actions">
                            <button class="copy-btn" onclick="copyMessage(this)" title="复制消息">
                                <span>📋</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input-container">
            <div class="chat-input-wrapper">
                <textarea id="chatInput" placeholder="请输入您想要策划的活动类型或需求..." rows="1" onkeydown="handleKeyDown(event)"
                    oninput="autoResize(this); toggleSendButton()"></textarea>
                <button id="sendButton" onclick="sendMessage()" disabled>
                    <span class="send-icon">📤</span>
                </button>
            </div>
            <div class="input-tips">
                <span>按 Enter 发送，Shift + Enter 换行</span>
            </div>
        </div>
    </div>

    <!-- 粒子背景 -->
    <div class="particles-bg" id="particles-js"></div>

    <script src="particles.js"></script>
    <script>
        // 全局变量
        let chatHistory = [];
        let isTyping = false;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function () {
            loadChatHistory();
            initializeParticles();
        });

        // 初始化粒子背景
        function initializeParticles() {
            if (typeof particlesJS !== 'undefined') {
                particlesJS('particles-js', {
                    particles: {
                        number: { value: 50 },
                        color: { value: '#ffffff' },
                        shape: { type: 'circle' },
                        opacity: { value: 0.3 },
                        size: { value: 3 },
                        move: {
                            enable: true,
                            speed: 1,
                            direction: 'none',
                            random: true,
                            straight: false,
                            out_mode: 'out',
                            bounce: false
                        }
                    },
                    interactivity: {
                        detect_on: 'canvas',
                        events: {
                            onhover: { enable: true, mode: 'repulse' },
                            onclick: { enable: true, mode: 'push' },
                            resize: true
                        }
                    },
                    retina_detect: true
                });
            } else {
                console.warn('particles.js 未加载');
            }
        }

        // 处理键盘事件
        function handleKeyDown(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        }

        // 自动调整输入框高度
        function autoResize(textarea) {
            textarea.style.height = 'auto';
            textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
        }

        // 切换发送按钮状态
        function toggleSendButton() {
            const chatInput = document.getElementById('chatInput');
            const sendButton = document.getElementById('sendButton');
            sendButton.disabled = chatInput.value.trim() === '' || isTyping;
        }

        // 发送消息
        async function sendMessage() {
            const chatInput = document.getElementById('chatInput');
            const message = chatInput.value.trim();

            if (message === '' || isTyping) return;

            // 添加用户消息
            addMessage(message, 'user');

            // 清空输入框
            chatInput.value = '';
            chatInput.style.height = 'auto';
            toggleSendButton();

            // 显示机器人正在输入
            showTypingIndicator();

            try {
                // 调用扣子API
                const response = await callCozeAPI(message);
                hideTypingIndicator();
                addMessage(response, 'bot');
            } catch (error) {
                hideTypingIndicator();
                console.error('API调用失败:', error);
                addMessage('抱歉，服务暂时不可用，请稍后再试。', 'bot');
                showNotification('API调用失败，请检查网络连接', 'warning');
            }
        }

        // 调用扣子API
        async function callCozeAPI(query) {
            const apiUrl = CONFIG.getApiUrl('/api/coze-proxy'); // 使用配置的API地址

            const requestBody = {
                bot_id: '7536146635006099498',
                user: 'activity_user_' + Date.now(),
                query: query,
                stream: false
            };

            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestBody)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            
            // 解析响应数据
            if (data.code === 0 && data.messages && data.messages.length > 0) {
                // 查找机器人的回复消息
                for (const message of data.messages) {
                    const content = message.content || '';
                    // 过滤掉系统消息和错误消息
                    if (!content.startsWith('{') && !content.startsWith('RPCError') && content.trim()) {
                        return content;
                    }
                }
                return '抱歉，我暂时无法理解您的活动策划需求，请换个方式描述。';
            } else {
                throw new Error(data.msg || '未知错误');
            }
        }

        // 添加消息到聊天区域
        function addMessage(text, sender, timestamp = null) {
            const chatMessages = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            const time = timestamp || getCurrentTime();

            messageDiv.className = `message ${sender}-message`;
            messageDiv.innerHTML = `
                <div class="message-avatar">${sender === 'user' ? '👤' : '🤖'}</div>
                <div class="message-content">
                    <div class="message-text">${formatMessage(text)}</div>
                    <div class="message-time">${time}</div>
                    <div class="message-actions">
                        <button class="copy-btn" onclick="copyMessage(this)" title="复制消息">
                            <span>📋</span>
                        </button>
                    </div>
                </div>
            `;

            chatMessages.appendChild(messageDiv);
            scrollToBottom();

            // 保存到历史记录
            const messageData = {
                text: text,
                sender: sender,
                timestamp: time,
                id: Date.now() + Math.random()
            };

            chatHistory.push(messageData);
            saveChatHistory();
        }

        // 格式化消息文本
        function formatMessage(text) {
            text = text.replace(/\n/g, '<br>');
            const urlRegex = /(https?:\/\/[^\s]+)/g;
            text = text.replace(urlRegex, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>');
            return text;
        }

        // 显示输入指示器
        function showTypingIndicator() {
            if (document.querySelector('.typing-indicator')) return;

            isTyping = true;
            toggleSendButton();

            const chatMessages = document.getElementById('chatMessages');
            const typingDiv = document.createElement('div');

            typingDiv.className = 'message bot-message typing-message';
            typingDiv.innerHTML = `
                <div class="message-avatar">🤖</div>
                <div class="message-content">
                    <div class="typing-indicator">
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                    </div>
                </div>
            `;

            chatMessages.appendChild(typingDiv);
            scrollToBottom();
        }

        // 隐藏输入指示器
        function hideTypingIndicator() {
            const typingMessage = document.querySelector('.typing-message');
            if (typingMessage) {
                typingMessage.remove();
            }
            isTyping = false;
            toggleSendButton();
        }

        // 复制消息
        function copyMessage(button) {
            const messageText = button.closest('.message-content').querySelector('.message-text');
            const text = messageText.innerText || messageText.textContent;

            navigator.clipboard.writeText(text).then(() => {
                const originalText = button.innerHTML;
                button.innerHTML = '<span>✅</span>';
                button.style.background = '#4CAF50';

                setTimeout(() => {
                    button.innerHTML = originalText;
                    button.style.background = '';
                }, 1000);
            }).catch(err => {
                console.error('复制失败:', err);
                // 降级方案：选中文本
                const range = document.createRange();
                range.selectNode(messageText);
                window.getSelection().removeAllRanges();
                window.getSelection().addRange(range);
            });
        }

        // 清空历史记录
        function clearHistory() {
            if (confirm('确定要清空所有对话历史吗？此操作不可撤销。')) {
                chatHistory = [];
                localStorage.removeItem('activityPlanningHistory');

                const chatMessages = document.getElementById('chatMessages');
                const welcomeMessage = chatMessages.querySelector('.welcome-message');
                chatMessages.innerHTML = '';
                if (welcomeMessage) {
                    chatMessages.appendChild(welcomeMessage);
                }

                showNotification('历史记录已清空', 'success');
            }
        }

        // 导出对话历史
        function exportHistory() {
            if (chatHistory.length === 0) {
                showNotification('暂无对话记录可导出', 'warning');
                return;
            }

            let exportText = '贝壳OC活动策划助手 - 对话记录\n';
            exportText += '导出时间: ' + new Date().toLocaleString() + '\n';
            exportText += '='.repeat(50) + '\n\n';

            chatHistory.forEach((msg) => {
                const sender = msg.sender === 'user' ? '用户' : '助手';
                exportText += `[${msg.timestamp}] ${sender}:\n${msg.text}\n\n`;
            });

            const blob = new Blob([exportText], { type: 'text/plain;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `活动策划记录_${new Date().toISOString().slice(0, 10)}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);

            showNotification('对话记录已导出', 'success');
        }

        // 保存聊天历史
        function saveChatHistory() {
            try {
                localStorage.setItem('activityPlanningHistory', JSON.stringify(chatHistory));
            } catch (error) {
                console.error('保存聊天历史失败:', error);
            }
        }

        // 加载聊天历史
        function loadChatHistory() {
            try {
                const saved = localStorage.getItem('activityPlanningHistory');
                if (saved) {
                    chatHistory = JSON.parse(saved);
                    chatHistory.forEach(msg => {
                        if (msg.text && msg.sender) {
                            addMessageToDOM(msg.text, msg.sender, msg.timestamp);
                        }
                    });
                }
            } catch (error) {
                console.error('加载聊天历史失败:', error);
                chatHistory = [];
            }
        }

        // 仅添加消息到DOM
        function addMessageToDOM(text, sender, timestamp) {
            const chatMessages = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');

            messageDiv.className = `message ${sender}-message`;
            messageDiv.innerHTML = `
                <div class="message-avatar">${sender === 'user' ? '👤' : '🤖'}</div>
                <div class="message-content">
                    <div class="message-text">${formatMessage(text)}</div>
                    <div class="message-time">${timestamp}</div>
                    <div class="message-actions">
                        <button class="copy-btn" onclick="copyMessage(this)" title="复制消息">
                            <span>📋</span>
                        </button>
                    </div>
                </div>
            `;

            chatMessages.appendChild(messageDiv);
        }

        // 滚动到底部
        function scrollToBottom() {
            const chatMessages = document.getElementById('chatMessages');
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 获取当前时间
        function getCurrentTime() {
            const now = new Date();
            return now.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 显示通知
        function showNotification(message, type = 'info') {
            const notification = document.createElement('div');
            notification.className = `notification notification-${type}`;
            notification.textContent = message;

            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: ${type === 'success' ? '#4CAF50' : type === 'warning' ? '#FF9800' : '#2196F3'};
                color: white;
                padding: 12px 20px;
                border-radius: 8px;
                z-index: 10000;
                animation: slideInRight 0.3s ease;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            `;

            document.body.appendChild(notification);

            setTimeout(() => {
                notification.style.animation = 'slideOutRight 0.3s ease';
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        }

        // 添加通知动画样式
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideInRight {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOutRight {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(style);
    </script>
</body>

</html>